package cn.ze.yygh.user.api;

import cn.ze.yygh.common.helper.JwtHelper;
import cn.ze.yygh.common.result.Result;
import cn.ze.yygh.model.user.UserInfo;
import cn.ze.yygh.user.service.UserInfoService;
import cn.ze.yygh.user.utils.ConstantWxPropertiesUtils;
import cn.ze.yygh.user.utils.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//微信操作的接口
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    //1.生成微信扫描二维码
    //返回生成二维码需要的参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(){
        System.out.println("getLoginParam");
        try {
            Map<String , Object> map = new HashMap<>();
            map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
            map.put("scope","snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL;
            //wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            map.put("redirect_uri","snsapi_login");
            map.put("redirect_uri",wxOpenRedirectUrl);
            map.put("state",System.currentTimeMillis()+"");
            return Result.ok(map);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }


    }

    //2.回调方法,得到回调信息
    @GetMapping("callback")
    public String callback(String code,String state){
        //获取临时票据
        System.out.println("code = :" + code);
        // 拿着code 和 微信id 和密匙 请求微信固定地址 得到...
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code);

        //使用httpclient请求
        try {
            String accesstokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println(accesstokenInfo);
            //从返回的字符串中获取 openid  和accesss_token
            JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //判断数据库是否存在扫码人的信息
            //根据openid 判断
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);

            if(userInfo == null){

                // 带着openid  和accesss_token再次请求微信地址
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl,access_token,openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(resultInfo);

                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                //用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //用户头像
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                //存入数据库
                userInfoService.save(userInfo);
            }

            //最终返回name 和 token字符串
            Map<String,Object> map = new HashMap<>();


            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //判断userinfo中是否有手机号 手机号返回openid
            //否则返回空

            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //使用JWT生成token
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL
                    + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"),"utf-8");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}
